<?php

declare(strict_types=1);

namespace app\model;

use app\admin\model\RsBrand;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 * 
 *
 * @mixin \think\Model
 * @property int $id
 * @property int $supplier_id 供应商id
 * @property string $sku_id 外部商品id
 * @property string $image
 * @property string $goods_name
 * @property int $brand_id 品牌id
 * @property int $category_id 商品分类id
 * @property bool $sku_type 货源商品类型 1 卡券商品 2 直充商品
 * @property bool $sku_state 货源的商品状态
 * @property int $market_price 市场价
 * @property int $cost_price 成本价
 * @property int $sale_price 销售价
 * @property bool $relate_state 关联状态 0未 1已关联
 * @property bool $shelf_state 0 下架 1上架 。需要结合relate_state
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 * @property string $deleted_at
 * @property string $type_name 充值类型
 * @property string $api_name 接口名称
 * @property int $sort 排序
 * @property-read \app\model\BaseSupplier $supplier
 * @property-read \app\admin\model\RsBrand $brand
 * @method static \think\db\Query onlyTrashed()
 * @method static \think\db\Query withTrashed()
 */
class CouponGoods extends CommonModel
{
    use SoftDelete;
    public $skuType = [1 => '卡券', 2 => '直充'];
    public $skuState = [0 => '已失效', 1 => '正常'];
    public $relateState = [0 => '未对接', 1 => '已对接', 2 => '匹配失败'];
    public $shelfState = [-1 => '未知初始状态', 0 => '已下架', 1 => '已上架'];


    /* 供应商 */
    public function supplier()
    {
        return $this->belongsTo(BaseSupplier::class, 'supplier_id');
    }

    /* 商品分类 */
    public function brand()
    {
        return $this->belongsTo(RsBrand::class, 'brand_id');
    }

    /**
     *  导入商品
     */
    public static function importGoods($data, $brandId, $type)
    {
        $keys = [2, 3, 4, 5, 7, 8];
        foreach ($keys as $key) {
            if (!isset($data[$key])) {
                return false;
            }
        }

        $supplier = '重庆璐付';
        $supplierId = Db::name('base_supplier')->where('name', $supplier)->value('id');
        if (empty($supplierId)) {
            $supplierId = Db::name('base_supplier')->insertGetId(['name' => $supplier, 'serv_type' => 3]);
        }
        $attr = ['卡密' => 1, '直充' => 2];
        $goods = self::where('sku_id', $data[4])->find();
        if (!$goods) {
            $goods = new self();
        }
        $goods->brand_id = $brandId;
        if (!empty($type)) {
            $goods->sku_type = $attr[$type];
        }
        $goods->goods_name = $data[2];
        $goods->api_name = $data[3];
        $goods->sku_id = $data[4];
        $goods->market_price = yuan2fen($data[5]);
//            $goods->price_rate=$data[6];
        $goods->cost_price = yuan2fen($data[7]);
        $goods->type_name = $data[8];
        $goods->supplier_id = $supplierId;
        $goods->save();

        return $goods->id;
    }

    /**
     *  商品对接
     *  type 1对接  2取消对接.
     */
    public function optionRelate($data)
    {
        if (!empty($data['ids'])) {
            if (1 == $data['type']) {
                self::where('id', 'in', $data['ids'])->save(['relate_state' => 1]);
            } else {
                self::where('id', 'in', $data['ids'])->save(['relate_state' => 0, 'shelf_state' => 0]);
            }
        } else {
            return  fail('设置失败，参数错误！');
        }

        return success('设置成功！');
    }

    /**
     *  商品上下架
     *  type 1上架  0下架.
     */
    public function optionShelf($data)
    {
        if (!empty($data['ids']) && isset($data['type'])) {
            self::where('id', 'in', $data['ids'])->save(['shelf_state' => $data['type']]);
        } else {
            return  fail('设置失败，参数错误！');
        }

        return success('设置成功！');
    }

    /**
     *  修改销售价.
     */
    public function optionSalePrice($data)
    {
        if (!empty($data['id']) && isset($data['sale_price'])) {
            $data['sale_price']=yuan2fen($data['sale_price']);
            self::where('id', '=', $data['id'])->save(['sale_price' => $data['sale_price']]);
        } else {
            return  fail('设置失败，参数错误！');
        }

        return success('设置成功！');
    }

    /**
     *  商品详情..
     **/
    public static function showDetail($data)
    {
        if (empty($data[ 'brand_id'])) {
            return  fail("失败，品牌不能为空！");
        }
        $list=self::where("brand_id", $data['brand_id'])
            ->where("relate_state", 1)
            ->where("shelf_state", 1)
            ->order('sort desc, id desc')
            ->select();
        $result=[];
        if ($list->isEmpty()) {
            return  fail("失败，当前商品未上架！");
        }
        $brand=RsBrand::where("id", $data['brand_id'])
            ->field("brand_name,brand_img,brand_info,account_type")
            ->find();
        $attr=$good=[];
        foreach ($list->toArray() as $nk=>$nv) {
            $good[$nv['type_name']]['type_name']=$nv['type_name'];
            $good[$nv['type_name']]['sku_type']=$nv['sku_type'];
            $attr['name']=self::getType($nv['goods_name']);
            $attr['good_id']=$nv['id'];
            $attr['market_price']=fen2yuan($nv['market_price']);
            $attr['sale_price']=fen2yuan($nv['sale_price']);
            $attr['sku_type'] = $nv['sku_type'];
            $good[$nv['type_name']]['list'][]=$attr;
        }
        $res['goods']=array_values($good);
        $res['brand']=$brand;
        return success('成功！', $res);
    }

    public static function getTypeOld($goodsName)
    {
        $result = strpos($goodsName, '周卡');
        switch ($goodsName) {
                case false !== strpos($goodsName, '天卡'):$result = '1天'; break;
                case false !== strpos($goodsName, '周卡'):$result = '7天'; break;
                case false !== strpos($goodsName, '月卡'):$result = '1个月'; break;
                case false !== strpos($goodsName, '季卡'):$result = '3个月'; break;
                case false !== strpos($goodsName, '半年卡'):$result = '6个月'; break;
                case false !== strpos($goodsName, '年卡'):$result = '12个月'; break;
            }

        return $result;
    }

    public static function getType($goodsName)
    {
        if (empty($goodsName)) {
            return '';
        }

        $pregList = [
            '/\d{1,}小时/',
            '/\d{1,}天/',
            '/\d{1,}个月/',
            '/\d{1,}月/',
        ];
        foreach ($pregList as $preg) {
            preg_match($preg, $goodsName, $matches);
            if (!empty($matches[0])) {
                return $matches[0];
            }
        }

        $typeList = [
            '1天' => [
                '天卡',
            ],
            '7天' => [
                '周卡',
            ],
            '1个月' => [
                '月卡', '月会员',
            ],
            '3个月' => [
                '季卡', '季会员', '季度会员',
            ],
            '6个月' => [
                '半年卡',
            ],
            '12个月' => [
                '年卡', '年会员',
            ],
        ];
        foreach ($typeList as $val => $list) {
            foreach ($list as $key) {
                if (false !== strpos($goodsName, $key)) {
                    return $val;
                }
            }
        }

        return '';
    }

    /**
     * 充值类型
     */
    public function rechargeType($brandId)
    {
        $list = self::where('brand_id', $brandId)
            ->field('id, sort, created_at, updated_at, shelf_state, type_name, brand_id')
            ->where('relate_state', 1)
            ->order('sort desc, id desc')
            ->select()
            ->toArray();
        $res = [];
        foreach ($list as $v) {
            if (empty($res[$v['type_name']])) {
                $res[$v['type_name']] = $v;
                continue;
            }
            if ($v['shelf_state'] == 1) {
                $res[$v['type_name']]['shelf_state'] = 1;
            }
        }
        unset($list);
        
        return array_values($res);
    }

    /**
     * 充值类型面额
     */
    public function rechargeAmount($brandId, $typeName)
    {
        $list = self::where('brand_id', $brandId)
            ->where('type_name', $typeName)
            ->field('id, sort, created_at, updated_at, shelf_state, type_name, goods_name')
            ->where('relate_state', 1)
            ->order('sort desc, id desc')
            ->select()
            ->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['amount_name'] = self::getType($v['goods_name']) . '会员';
        }
        return $list;
    }

    /**
     * 修改排序
     */
    public function changeSort($data)
    {
        self::where('id', $data['id'])
            ->update([
                'sort' => $data['sort']
            ]);

        return true;
    }

    /**
     * 修改产品上下架状态
     */
    public function changeShelfState($data)
    {
        if (!empty($data['brand_id'])) {
            $where[] = ['brand_id', '=', $data['brand_id']];
            $where[] = ['type_name', '=', $data['type_name']];
        } else {
            $where[] = ['id', '=', $data['id']];
        }
        self::where($where)->update([
            'shelf_state' => $data['shelf_state'],
        ]);

        return true;
    }
}
